package cn.cdeden.system.controller.system;

import cn.cdeden.common.core.domain.R;
import cn.cdeden.common.core.utils.page.TableDataInfo;
import cn.cdeden.common.mybatis.core.page.PageQuery;
import cn.cdeden.system.domain.FilesTreeRecycle;
import cn.cdeden.system.domain.RecoverFilePath;
import cn.cdeden.system.domain.dto.FilesTreeRecycleParam;
import cn.cdeden.system.domain.enums.TreeEnum;
import cn.cdeden.system.domain.enums.TreeTypeEnum;
import cn.cdeden.system.domain.vo.FilesTreeRecycleVo;
import cn.cdeden.system.recycle.RecycleFactory;
import cn.cdeden.system.recycle.RecycleInterface;
import cn.cdeden.system.service.FilesTreeRecycleService;
import io.undertow.util.BadRequestException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 文件:二级回收站处理模块
 */
@Controller
@Slf4j
//@Api(tags = "文件:二级回收站处理模块")
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/recycleBin/foxBase")
public class FilesTreeFoxBaseRecycleController {


    private final FilesTreeRecycleService recycleService;
    private final RecycleFactory factory ;



    /**
     * 查询二级回收站
     * @param param
     * @param pageable
     * @return
     */
//    @Log("查询二级回收站")
//    @ApiOperation("查询二级回收站")
    @GetMapping(value = "/select")
    @ResponseBody
    public R<TableDataInfo<FilesTreeRecycleVo>> selectRecycle(FilesTreeRecycleParam param, PageQuery pageable) throws BadRequestException {
        TreeEnum treeEnum = TreeEnum.find(param.getFileTreeType());
        if (treeEnum == null){
            throw new BadRequestException("非法请求");
        }
        TableDataInfo<FilesTreeRecycleVo> info = recycleService.selectRecycleAll(param,pageable);
        return R.ok(info);
    }

    /**
     * 二级回收站还原数据
     * @param path
     * @return
     */
//    @Log("二级回收站还原数据")
//    @ApiOperation("二级回收站还原数据")
    @PostMapping(value = "/recoverFile/path")
    @ResponseBody
//    @ApiImplicitParams({
//    })
    @Transactional
    public R recoverFilePath(@RequestBody RecoverFilePath path ) throws BadRequestException {
        if (StringUtils.isEmpty(path.getType())){
            throw new BadRequestException("非法请求");
        }

        RecycleInterface recycle = null;
        try{
            recycle = factory.getRecycle(path.getType());
        }catch (Exception e){
            throw new BadRequestException("错误请求类型");
        }

        List<FilesTreeRecycle> list = recycleService.selectRecycle(path.getId(),path.getIds(), path.getParentId(), path.getType());
//        List<Long> collect = list.stream().map(FilesTreeRecycle::getIds).collect(Collectors.toList()).stream().flatMap(Collection::stream).collect(Collectors.toList()); //取出全部IDS
        Set<Long> collect = new HashSet<>();
        list.forEach(recycle1 -> {
            if (StringUtils.equalsIgnoreCase(recycle1.getType(), TreeTypeEnum.FOLDER.getType())
                && CollectionUtils.isNotEmpty(recycle1.getSonDataList()) ){
                Set<Long> test = test(recycle1);
                collect.addAll(test);
            }
            collect.add(recycle1.getId());
        });

        R baseRespResult = null;
        try {
            baseRespResult = recycle.foxBaseRecoverFileChooseAPath(list);
//            baseRespResult = recycle.foxBaseRecoverFileChooseAPath(list);
        }catch (Exception e){
            throw new RuntimeException(e.getMessage()+"恢复数据错误");
        }
        recycleService.removeByIds(collect);
        return baseRespResult;
    }

    public Set<Long> test(FilesTreeRecycle recycle){
        Set<Long> collect = new HashSet<>();
        recycle.getSonDataList().forEach(recycle1 -> {
            if (StringUtils.equalsIgnoreCase(recycle1.getType(), TreeTypeEnum.FOLDER.getType())
                && CollectionUtils.isNotEmpty(recycle1.getSonDataList()) ){
                Set<Long> test = test(recycle1);
                collect.addAll(test);
            }
            collect.add(recycle1.getId());
        });
        return  collect ;
    }


    /**
     * 二级回收站全部删除
     * @param type
     * @return
     */
//    @Log("二级回收站全部删除")
//    @ApiOperation("二级回收全部删除")
    @GetMapping(value = "/deleteAll")
    @ResponseBody
//    @ApiImplicitParams({
//    })
    public R deleteAll(@RequestParam(value = "type",required = false) String type ) {
        boolean b = false;
        if (StringUtils.isEmpty(type)){
            b = recycleService.deleteAll();
        }else {
            b = recycleService.delete(type);
        }
        return b ?  R.ok() : R.fail("删除失败");
//        return b ?  BaseRespResult.success() : BaseRespResult.errorResult("删除失败");
    }


}
